<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属机构" prop="institutionId">
        <el-select v-model="queryParams.institutionId" placeholder="请选择机构" style="width: 140px;" clearable>
          <el-option v-for="dict in institutions" :key="dict.id" :label="dict.institutionname" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="选择团队" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择团队" style="width: 120px;" clearable>
          <el-option
            v-for="dict in teams"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <!-- 完成时间 -->
      <el-form-item label="完成时间" prop="finishTime">
        <el-date-picker clearable v-model="queryParams.finishTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择完成时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['service_record:service_record:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="service_recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="服务状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="audit_tatus_five" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- 完成时间 -->
      <el-table-column label="完成时间" align="center" prop="finishTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="取消时间" align="center" prop="cancellationTime" /> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 计算服务状态为1：已完成的量count -->
    <div>
      <ul>
        <li>
          已完成数量：{{ service_recordList.filter(item => item.status === 1).length }}
        </li>
      </ul>
    </div>
    <!-- 计算服务状态为2：已取消的量count -->
    <div>
      <ul>
        <li>
          已取消数量：{{ service_recordList.filter(item => item.status === 2).length }}
        </li>
      </ul>
    </div>
    <!-- 将完成日期进行分月计算 -->
    <div>
      <ul>
        <li v-for="(count, month) in monthlyCounts" :key="month">
          {{ month }}月：{{ count }}条
        </li>
      </ul>
    </div>

    <!-- 以横坐标为时间，纵坐标为服务完成量1 ，生成柱状图 -->
    <div id="service-chart" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script setup name="Service_record">
import { listService_record, getService_record, delService_record, addService_record, updateService_record } from "@/api/service_record/service_record";
import { useRouter } from "vue-router";
import { listDoctor } from "@/api/system/doctor";
import { listResident } from "@/api/resident/resident";
import { listInstitution } from "@/api/system/institution";
import { listItem } from "@/api/item/item";
import { listTeam } from "@/api/system/team";
import { getUserProfile } from "@/api/system/user";
import * as echarts from 'echarts';

const { proxy } = getCurrentInstance();
const { years, audit_tatus_five, package_type, service_locations } = proxy.useDict('years', 'audit_tatus_five', 'package_type', 'service_locations');

const service_recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 用户信息
const state = reactive({
  user: {},
  roleGroup: {},
  postGroup: {}
});
function getUser() {
  getUserProfile().then(response => {
    state.user = response.data;
    console.log(state.user);
    state.roleGroup = response.roleGroup;
    state.postGroup = response.postGroup;
  });
}
getUser();

// 定义一个service_items数组，用于存储服务项目数据
const service_items = ref([]);
// 定义一个方法、动态获取服务项目数据
function getService_items() {
  listItem().then(response => {
    service_items.value = response.rows;
    console.log(service_items.value);
  });
}
// 调用getService_items方法，获取服务项目数据
getService_items();

// 定义一个institutions数组，用于存储机构数据
const institutions = ref([]);
// 定义一个方法、动态获取机构数据
function getInstitutions() {
  listInstitution().then(response => {
    institutions.value = response.rows;
    // console.log(institutions.value);
  });
}
// 调用getInstitutions方法，获取机构数据
getInstitutions();

// 定义一个teams数组，用于存储团队数据
const teams = ref([]);
// 定义一个方法、动态获取团队数据
function getTeams() {
  listTeam().then(response => {
    teams.value = response.rows;
    console.log(teams.value);
  });
}
// 调用getTeams方法，获取团队数据
getTeams();

// 定义一个users数组，用于存储用户数据
const users = ref([]);
// 定义一个方法、动态获取用户数据
function getUsers() {
  listResident().then(response => {
    users.value = response.rows;
    console.log(users.value);
  });
}
// 调用getUsers方法，获取用户数据
getUsers();

// 定义一个doctors数组，用于存储医生数据
const doctors = ref([]);
// 定义一个方法、动态获取医生数据
function getDoctors() {
  listDoctor().then(response => {
    doctors.value = response.rows;
    // console.log(doctors.value);
  });
}
// 调用getDoctors方法，获取医生数据
getDoctors();
// 详情页跳转
const router = useRouter();
const handleDetail = (row) => {
  const ids = row.id;
  router.push({ path: 'servicexiangqing', query: { id: ids } });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    teamId: null,
    institutionId: null,
    packageId: null,
    status: null,
    location: null,
    finishTime: null,
    appointmentTime: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

// 用于存储分月统计的结果
const monthlyCounts = ref({});

/** 查询服务记录列表 */
function getList() {
  loading.value = true;
  listService_record(queryParams.value).then(response => {
    // 过滤服务状态为1和2的记录
    service_recordList.value = response.rows.filter(item => item.status === 1 || item.status === 2);
    console.log(service_recordList.value);
    // 更新 total 为过滤后的记录数
    total.value = service_recordList.value.length;

    // 分月统计服务状态为 1 的记录
    monthlyCounts.value = {};
    service_recordList.value.forEach(item => {
      if (item.status === 1) {
        const date = new Date(item.finishTime);
        const month = date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0');
        monthlyCounts.value[month] = (monthlyCounts.value[month] || 0) + 1;
      }
    });

    // 生成柱状图
    const chartDom = document.getElementById('service-chart');
    const myChart = echarts.init(chartDom);
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: Object.keys(monthlyCounts.value),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: Object.values(monthlyCounts.value),
          type: 'bar',
          itemStyle: {
            color: '#1890ff'
          }
        }
      ]
    };
    myChart.setOption(option);

    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    organizationId: null,
    teamId: null,
    institutionId: null,
    doctorId: null,
    packageId: null,
    itemId: null,
    status: null,
    location: null,
    appointmentTime: null,
    submissionTime: null,
    auditTime: null,
    auditorId: state.user.userName,
    cancellationTime: null,
    cancellationReason: null,
    finishTime: null,
    remark: null
  };
  proxy.resetForm("service_recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service_record/service_record/export', {
    ...queryParams.value
  }, `service_record_${new Date().getTime()}.xlsx`)
}

getList();
</script>    